package com.wallezhou.upload;

import com.wallezhou.upload.servlet.FileMergeServelet;
import com.wallezhou.upload.servlet.FileUploadServlet;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.MultipartConfigElement;
import java.io.File;

@Configuration
public class ServletConfiguration {

    @Bean
    public ServletRegistrationBean<FileUploadServlet> fileUploadServletRegistration() {
        ServletRegistrationBean<FileUploadServlet> servletRegistrationBean = new ServletRegistrationBean<>(new FileUploadServlet(), "/file/upload");
        servletRegistrationBean.setMultipartConfig(multipartConfigElement());//支持multipart请求
        servletRegistrationBean.addInitParameter(FileUploadServlet.TARGETDIR, "D://temp//chunks");//这个值设置与FileMergeServelet一致
        return servletRegistrationBean;
    }

    @Bean
    public ServletRegistrationBean<FileMergeServelet> fileMergeServeletRegistration() {
        ServletRegistrationBean<FileMergeServelet> servletRegistrationBean = new ServletRegistrationBean<>(new FileMergeServelet(), "/file/merge");
        servletRegistrationBean.addInitParameter(FileMergeServelet.TARGETDIR, "D://temp//chunks");//这个值设置与FileUploadServlet一致
        return servletRegistrationBean;
    }


    /**
     * 配置上传文件临时目录
     *
     * @return
     */
    private MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String path = System.getProperty("user.dir");
        File tmpFile = new File(path);    // 如果临时目录不存在则创建
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        // 明确指定上传文件的临时目录
        factory.setLocation(path);
        return factory.createMultipartConfig();
    }
}
